package com.etoak.common.web.handler;


import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class ClobalExceptionHandler {
    /*
    处理 CustomException 异常
     */
    @ExceptionHandler
    public ResultVO<Object> handle(CustomException e){
        log.error(e.getMessage(), e);
        return ResultVO.failed(e.getMessage());
    }

    @ExceptionHandler
    public ResultVO<Object> handle(MethodArgumentNotValidException e){
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().stream().map(ObjectError::getObjectName).collect(Collectors.joining(";"));
        return ResultVO.failed(message);
    }
    @ExceptionHandler
    public ResultVO<Object> handle(Exception e){
        log.error(e.getMessage(), e);
        return ResultVO.failed(e.getMessage());
    }
    /**
     * Http 请求方法错误   405
     */
    @ExceptionHandler
    public ResultVO<Object> handle(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return ResultVO.failed(e.getMessage());
    }

    /**
     * Http 请求参数类型错误  415
     */
    @ExceptionHandler
    public ResultVO<Object> handle(HttpMediaTypeNotSupportedException e) {
        log.error(e.getMessage(), e);
        return ResultVO.failed(e.getMessage());
    }
}
